
import axios from 'axios'
// import qs from 'qs'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from './auth'

const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 90000
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }

    // if(config.method === 'get'){
    //   //如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
    //   config.paramsSerializer = function(params) {
    //       return qs.stringify(params, {arrayFormat: 'repeat'})
    //   }
    // }
    config.params = { ...config.params, client: 'admin', source: 1 }
    return config
  },

  error => {
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code !== 200 && res.code !== 201 && res.code !== 204) {
      // 303:非法的token; 301:Token 过期了;
      if (res.code === 303 || res.code === 301) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()
            store.commit('SET_TOKEN', '')
          })
        }).catch(() => {
        })
      } else {
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
